<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card" v-show="showSearch">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="药剂名称/订单号">
              <el-input v-model="queryParams.nameOrNumber" placeholder="请输入药剂名称或采购订单编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购状态">
              <el-select v-model="queryParams.purchaseStatus" placeholder="请选择采购状态" clearable style="width: 100%">
                <el-option label="全部" value="" />
                <el-option label="待审核" :value="0" />
                <el-option label="待入库" :value="1" />
                <el-option label="已入库" :value="2" />
                <el-option label="已取消" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购日期">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon class="el-icon--left">
            <Plus />
          </el-icon>
          新增采购
        </el-button>
        <el-button type="success" @click="handleExport" :loading="exportLoading">
          <el-icon class="el-icon--left">
            <Download />
          </el-icon>
          导出
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon class="el-icon--left">
            <Delete />
          </el-icon>
          批量删除
        </el-button>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="purchaseOrderNumber" label="订单编号" width="160" align="center" />
        <el-table-column prop="reagentName" label="药剂名称" align="center" />
        <el-table-column prop="specification" label="规格" align="center" width="120" />
        <el-table-column prop="purchaseQuantity" label="采购数量" align="center" width="100" />
        <el-table-column prop="unitPrice" label="单价(元)" align="center" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.unitPrice) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额(元)" align="center" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaseDate" label="采购日期" align="center" width="120">
          <template #default="{ row }">
            {{ formatDate(row.purchaseDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" align="center" />
        <el-table-column prop="purchaseStatus" label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.purchaseStatus)">
              {{ getStatusName(row.purchaseStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row.id)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)"
              v-if="row.purchaseStatus === '0'">编辑</el-button>
            <el-button type="success" size="small" @click="handleApprove(row)"
              v-if="row.purchaseStatus === '0'">审核</el-button>
            <el-button type="danger" size="small" @click="handleCancel(row)"
              v-if="row.purchaseStatus !== '3'">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="药剂名称" prop="reagentName">
              <el-input v-model="form.reagentName" placeholder="请输入药剂名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="药剂类型" prop="drugType">
              <el-select v-model="form.drugType" placeholder="请选择药剂类型" style="width: 100%">
                <el-option v-for="item in drugTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入药剂规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购数量" prop="purchaseQuantity">
              <el-input-number v-model="form.purchaseQuantity" :min="1" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价(元)" prop="unitPrice">
              <el-input-number v-model="form.unitPrice" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额(元)">
              <el-input :value="calculateTotalAmount" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker v-model="form.purchaseDate" type="date" placeholder="选择采购日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable style="width: 100%">
                <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="采购说明">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入采购说明" maxlength="200"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialog.visible" title="采购详情" width="900px">
      <el-descriptions v-if="detailData" :column="2" border>
        <el-descriptions-item label="订单编号">{{ detailData.purchaseOrderNumber }}</el-descriptions-item>
        <el-descriptions-item label="采购状态">
          <el-tag :type="getStatusTagType(detailData.purchaseStatus)">
            {{ getStatusName(detailData.purchaseStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="药剂名称">{{ detailData.reagentName }}</el-descriptions-item>
        <el-descriptions-item label="药剂类型">{{ getDrugTypeName(detailData.drugType) }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{ detailData.specification }}</el-descriptions-item>
        <el-descriptions-item label="采购数量">{{ detailData.purchaseQuantity }}</el-descriptions-item>
        <el-descriptions-item label="单价">{{ formatCurrency(detailData.unitPrice) }} 元</el-descriptions-item>
        <el-descriptions-item label="总金额">{{ formatCurrency(detailData.totalAmount) }} 元</el-descriptions-item>
        <el-descriptions-item label="采购日期">{{ formatDate(detailData.purchaseDate) }}</el-descriptions-item>
        <el-descriptions-item label="预计交货日期">{{ formatDate(detailData.expectedDeliveryDate) }}</el-descriptions-item>
        <el-descriptions-item label="实际交货日期">{{ formatDate(detailData.actualDeliveryDate) }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ detailData.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="供应商联系人">{{ detailData.supplierContactPerson }}</el-descriptions-item>
        <el-descriptions-item label="供应商电话">{{ detailData.supplierContactNumber }}</el-descriptions-item>
        <el-descriptions-item label="采购说明">{{ detailData.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="审批人">{{ detailData.approvalOperatorName || '未审批' }}</el-descriptions-item>
        <el-descriptions-item label="审批时间">{{ formatDateTime(detailData.approvalTime) }}</el-descriptions-item>
        <el-descriptions-item label="审批意见">{{ detailData.approvalComments || '无' }}</el-descriptions-item>
        <el-descriptions-item label="物流公司">{{ detailData.deliveryCompany || '无' }}</el-descriptions-item>
        <el-descriptions-item label="物流单号">{{ detailData.trackingNumber || '无' }}</el-descriptions-item>
        <el-descriptions-item label="收货时间">{{ formatDateTime(detailData.receiptTime) }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailData.creator }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="approveDialog.visible" title="审核采购单" width="600px">
      <el-form ref="approveFormRef" :model="approveForm" :rules="approveRules" label-width="120px">
        <el-form-item label="预计交货日期" prop="expectedDeliveryDate">
          <el-date-picker v-model="approveForm.expectedDeliveryDate" type="date" placeholder="选择预计交货日期"
            value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="审批意见" prop="approvalComments">
          <el-input v-model="approveForm.approvalComments" type="textarea" :rows="3" placeholder="请输入审批意见" />
        </el-form-item>
        <el-form-item label="物流公司">
          <el-input v-model="approveForm.deliveryCompany" placeholder="请输入物流公司" />
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="approveForm.trackingNumber" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// API导入
import {
  getSupplierList,
  getPharmaceuticalPurchaseList,
  getPharmaceuticalPurchaseDetail,
  addPharmaceuticalPurchase,
  updatePharmaceuticalPurchase,
  approvePharmaceuticalPurchase,
  cancelPharmaceuticalPurchase,
  deletePharmaceuticalPurchase,
  exportPharmaceuticalPurchase,
  getMedicineSupplierTypeList // 新增药剂类型接口
} from '@/api/prod_operate/prod_run/drug_manage/procurement'

const showSearch = ref(true)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nameOrNumber: '',
  purchaseStatus: '',
  startTime: '',
  endTime: ''
})

const dateRange = ref([])

// 表单数据
const form = reactive({
  id: undefined,
  reagentName: '',
  drugType: '',
  specification: '',
  purchaseQuantity: 1,
  unitPrice: 0,
  purchaseDate: dayjs().format('YYYY-MM-DD'),
  supplierId: undefined,
  remark: ''
})

// 审核表单数据
const approveForm = reactive({
  id: undefined,
  expectedDeliveryDate: '',
  approvalComments: '',
  deliveryCompany: '',
  trackingNumber: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: '新增采购',
  isEdit: false
})

const detailDialog = reactive({
  visible: false
})

const approveDialog = reactive({
  visible: false
})

// 表格数据
const tableData = ref([])
const supplierOptions = ref([])
const drugTypeOptions = ref([]) // 改为空数组，从接口获取
const total = ref(0)
const loading = ref(false)
const exportLoading = ref(false)
const selectedRows = ref([])
const formRef = ref()
const approveFormRef = ref()
const detailData = ref(null)

// 表单验证规则
const rules = reactive({
  reagentName: [
    { required: true, message: '请输入药剂名称', trigger: 'blur' }
  ],
  drugType: [
    { required: true, message: '请选择药剂类型', trigger: 'change' }
  ],
  purchaseQuantity: [
    { required: true, message: '请输入采购数量', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' }
  ],
  purchaseDate: [
    { required: true, message: '请选择采购日期', trigger: 'change' }
  ],
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ]
})

const approveRules = reactive({
  expectedDeliveryDate: [
    { required: true, message: '请选择预计交货日期', trigger: 'change' }
  ],
  approvalComments: [
    { required: true, message: '请输入审批意见', trigger: 'blur' }
  ]
})

// 计算属性
const calculateTotalAmount = computed(() => {
  return (form.purchaseQuantity * form.unitPrice).toFixed(2)
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD')
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化金额
const formatCurrency = (value) => {
  if (!value) return '0.00'
  return parseFloat(value).toFixed(2)
}

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    '0': '待审核',
    '1': '待入库',
    '2': '已入库',
    '3': '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签样式
const getStatusTagType = (status) => {
  const typeMap = {
    '0': 'warning', // 待审核
    '1': 'primary', // 待入库
    '2': 'success', // 已入库
    '3': 'danger'   // 已取消
  }
  return typeMap[status] || 'info'
}

// 获取药剂类型名称
const getDrugTypeName = (type) => {
  const typeItem = drugTypeOptions.value.find(item => item.dictValue === type)
  return typeItem ? typeItem.dictLabel : '未知类型'
}

// 获取供应商列表
const fetchSupplierList = async () => {
  try {
    const res = await getSupplierList()
    supplierOptions.value = res.data || []
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败')
  }
}

// 获取药剂类型列表
const fetchDrugTypeList = async () => {
  try {
    const res = await getMedicineSupplierTypeList()
    drugTypeOptions.value = res.data || []
  } catch (error) {
    console.error('获取药剂类型列表失败:', error)
    ElMessage.error('获取药剂类型列表失败')
  }
}

const syncDateRangeToQuery = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.startTime = dateRange.value[0]
    queryParams.endTime = dateRange.value[1]
  } else {
    queryParams.startTime = ''
    queryParams.endTime = ''
  }
}

// 获取药剂采购列表
const getList = async () => {
  try {
    loading.value = true
    syncDateRangeToQuery()

    const res = await getPharmaceuticalPurchaseList(queryParams)
    tableData.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取药剂采购列表失败:', error)
    ElMessage.error('获取药剂采购列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  Object.assign(queryParams, {
    pageNum: 1,
    nameOrNumber: '',
    purchaseStatus: '',
    startTime: '',
    endTime: ''
  })
  getList()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增采购
const handleAdd = async () => {
  await Promise.all([fetchSupplierList(), fetchDrugTypeList()])
  dialog.title = '新增采购'
  dialog.isEdit = false
  dialog.visible = true
}

// 编辑采购
const handleEdit = async (row) => {
  await Promise.all([fetchSupplierList(), fetchDrugTypeList()])
  Object.assign(form, {
    id: row.id,
    reagentName: row.reagentName,
    drugType: row.drugType,
    specification: row.specification,
    purchaseQuantity: row.purchaseQuantity,
    unitPrice: row.unitPrice,
    purchaseDate: row.purchaseDate,
    supplierId: row.supplierId,
    remark: row.remark
  })
  dialog.title = '编辑采购'
  dialog.isEdit = true
  dialog.visible = true
}

// 查看详情
const handleView = async (id) => {
  try {
    const res = await getPharmaceuticalPurchaseDetail(id)
    detailData.value = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取采购详情失败:', error)
    ElMessage.error('获取采购详情失败')
  }
}

// 审核采购
const handleApprove = (row) => {
  approveForm.id = row.id
  approveForm.expectedDeliveryDate = ''
  approveForm.approvalComments = ''
  approveForm.deliveryCompany = ''
  approveForm.trackingNumber = ''
  approveDialog.visible = true
}

// 提交审核
const submitApprove = async () => {
  try {
    await approveFormRef.value.validate()
    await approvePharmaceuticalPurchase(approveForm)
    ElMessage.success('审核成功')
    approveDialog.visible = false
    getList()
  } catch (error) {
    console.error('审核失败:', error)
  }
}

// 取消采购
const handleCancel = (row) => {
  ElMessageBox.confirm(`确认取消采购单 "${row.purchaseOrderNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await cancelPharmaceuticalPurchase(row.id)
      ElMessage.success('取消成功')
      getList()
    } catch (error) {
      console.error('取消失败:', error)
      ElMessage.error('取消失败')
    }
  }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  const ids = selectedRows.value.map(item => item.id)
  ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deletePharmaceuticalPurchase(ids.join(','))
      ElMessage.success('批量删除成功')
      selectedRows.value = []
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => { })
}

// 导出数据
const handleExport = async () => {
  try {
    exportLoading.value = true
    syncDateRangeToQuery()
    const params = { ...queryParams }
    await exportPharmaceuticalPurchase(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (dialog.isEdit) {
      await updatePharmaceuticalPurchase(form)
      ElMessage.success('更新成功')
    } else {
      await addPharmaceuticalPurchase(form)
      ElMessage.success('新增成功')
    }

    dialog.visible = false
    getList()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 初始化
onMounted(() => {
  getList()
  fetchDrugTypeList() // 初始化时加载药剂类型列表
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  font-family: inherit;
  line-height: 1.5;
}
</style>